import { ContextTag } from '../context-tag/context-tag';

/**
 * 模板上下文项
 *
 * @author chitanda
 * @date 2022-01-13 10:01:02
 * @export
 * @class ContextItem
 */
export class ContextItem {
  /**
   * 子项
   *
   * @author chitanda
   * @date 2022-01-13 10:01:38
   * @type {ContextItem[]}
   */
  children: ContextItem[] = [];
  /**
   * 开始节点
   *
   * @author chitanda
   * @date 2022-01-13 10:01:58
   * @type {ContextTag}
   */
  start!: ContextTag;
  /**
   * 结束节点
   *
   * @author chitanda
   * @date 2022-01-13 10:01:04
   * @type {ContextTag}
   */
  end!: ContextTag;

  /**
   * 设置启动节点
   *
   * @author chitanda
   * @date 2022-01-13 10:01:42
   * @param {ContextTag} tag
   */
  setStart(tag: ContextTag) {
    this.start = tag;
  }

  /**
   * 设置结束节点
   *
   * @author chitanda
   * @date 2022-01-13 10:01:48
   * @param {ContextTag} tag
   */
  setEnd(tag: ContextTag) {
    this.end = tag;
  }

  /**
   * 添加子项
   *
   * @author chitanda
   * @date 2022-01-13 10:01:27
   * @param {ContextItem} child
   */
  addChildren(child: ContextItem) {
    this.children.push(child);
  }

  /**
   * 计算上下文变量
   *
   * @author chitanda
   * @date 2022-01-13 11:01:58
   * @param {number} offset
   * @return {*}  {string[]}
   */
  calcCompletionDomain(offset: number): ContextTag[] {
    const vars: ContextTag[] = [this.start];
    const child = this.children.find(item => item.isCurrentDomain(offset));
    if (child) {
      vars.push(...child.calcCompletionDomain(offset));
    }
    return vars;
  }

  /**
   * 是否为当前域下内容
   *
   * @author chitanda
   * @date 2022-01-13 11:01:44
   * @param {number} offset
   * @return {*}  {boolean}
   */
  isCurrentDomain(offset: number): boolean {
    if (this.start.index + this.start.length < offset && this.end.index > offset) {
      return true;
    }
    return false;
  }
}
